package fire.and.near.challenger.database.crypto;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

import android.util.Base64;
import android.util.Log;

public class CryptoUtils {

	private String SecretKey = "silensifire12345";
	
	public CryptoUtils()
	{
		// Hi there, whatchadoin?
	}
	
	public String encrypt(String text) throws Exception
	{	
		try {           
	        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
	        byte[] keyBytes= new byte[16];
	        byte[] b= SecretKey.getBytes("UTF-8");
	        int len= b.length;
	        if (len > keyBytes.length) len = keyBytes.length;
	        System.arraycopy(b, 0, keyBytes, 0, len);
	        SecretKeySpec keySpec = new SecretKeySpec(keyBytes, "AES");
	        IvParameterSpec ivSpec = new IvParameterSpec(keyBytes);
	        cipher.init(Cipher.ENCRYPT_MODE,keySpec,ivSpec);

	        byte[] results = cipher.doFinal(text.getBytes("UTF-8"));
	        String result = Base64.encodeToString(results, 0);
	        
	        return result;

	    } catch (Exception e) {
	        return null;
	    }
	}
	
	public String decrypt(String code) throws Exception
	{
		try {           
	        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
	        byte[] keyBytes= new byte[16];
	        byte[] b= SecretKey.getBytes("UTF-8");
	        int len= b.length;
	        if (len > keyBytes.length) len = keyBytes.length;
	        System.arraycopy(b, 0, keyBytes, 0, len);
	        SecretKeySpec keySpec = new SecretKeySpec(keyBytes, "AES");
	        IvParameterSpec ivSpec = new IvParameterSpec(keyBytes);
	        cipher.init(Cipher.DECRYPT_MODE,keySpec,ivSpec);
	        byte[] results = cipher.doFinal(Base64.decode(code, 0));
	        
	        return new String(results, "UTF-8");
	    } catch (Exception e) {
	        Log.d("decryption", e.getMessage());
	        return null;
	    }
	}
}
